package org.backend.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.backend.pojo.entity.Favor;
import org.backend.pojo.dto.ProductSummaryDTO;
import org.backend.pojo.entity.Product;
import org.backend.enums.ProductStatus;
import org.backend.pojo.entity.Transaction;
import org.backend.pojo.vo.FavorWithProductVO;
import org.backend.pojo.vo.ProductCategoriesVO;
import org.backend.repository.ProductRepository;
import org.backend.repository.TransactionRepository;
import org.backend.service.ProductService;
import org.backend.utils.ApiResponse;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private TransactionRepository transactionRepository;

    @Override
    public ApiResponse<?> findAll(String userId, String openid, String type) {
        if (type == null) {
            type = "full";
        }
        if (type.equals("full")) { // 获取对应用户ID的所有商品
            List<Product> proList;
            if (openid != null) { // 微信小程序用户的userId都为-1
                userId = "-1";
                proList = productRepository.findAll(userId, openid);
            } else {
                proList = productRepository.findAll2Web(userId);
            }

            for (Product pro : proList) {
                ProductStatus status = ProductStatus.fromStatus(pro.getStatus());
                pro.setDescStatus(status.getDesc());
            }
            log.info("proList: {}", proList);
            return new ApiResponse<>(200, proList, "获取成功");
        } else { // 获取商品可视化数据
            System.out.println("被执行了吗");
            List<ProductSummaryDTO> proList = productRepository.findProdStats(userId);
            return new ApiResponse<>(200, proList, "获取成功");
        }

    }

    @Override
    public ResponseEntity<String> publish(Product product) {
        if (product.getName() == null || product.getName().isEmpty()
                || product.getPrice() == null
                || product.getPrice().doubleValue() <= 0

        ) {
            throw new IllegalArgumentException("商品名字和价格不能为空");
        } else {
            String descStatus = product.getDescStatus();
            if (descStatus == null) {
                product.setStatus(2);
            } else {
                product.setStatus(ProductStatus.fromDesc(descStatus)); // 实体类转换状态
            }
            int rowsAffected = productRepository.publish(product);
            if (rowsAffected > 0) {
                return ResponseEntity.ok("发布成功");
            } else {
                return ResponseEntity.noContent().build();
            }
        }
    }

    @Override
    public ResponseEntity<String> delete(Product product) {
        Integer productId = product.getProductId();
        if (productId != null && productRepository.delete(productId) > 0) {
            return ResponseEntity.ok("删除成功");
        } else {
            return ResponseEntity.noContent().build();
        }
    }

    @Override
    @Transactional
    public ResponseEntity<String> revise(Product product) {
        String descStatus = product.getDescStatus();
        product.setStatus(ProductStatus.fromDesc(descStatus));
        log.info("product: {}", product);
        if (productRepository.revise(product) > 0 && product.getProductId() != null) {
            return ResponseEntity.ok("编辑成功");
        } else {
            return ResponseEntity.noContent().build();
        }
    }

    @Override
    public ApiResponse<List<Product>> getAllProList() {
        List<Product> list = productRepository.getAllProList();
        if (!list.isEmpty()) {
            return ApiResponse.success(list);
        }
        return ApiResponse.error("获取失败");
    }

    @Override
    public ApiResponse<List<Product>> getPopularProducts() {
        List<Product> list = productRepository.getPopularProducts();
        if (!list.isEmpty()) {
            return ApiResponse.success(list);
        }
        return ApiResponse.error("获取失败");
    }

    @Override
    public ApiResponse<Product> getProductById(Integer productId) {
        Product product = productRepository.getProductById(productId);
        if (product != null) {
            return ApiResponse.success(product);
        }
        return ApiResponse.error("查找错误");
    }

    @Override
    public ApiResponse<List<ProductCategoriesVO>> getProductCategories() {
        List<ProductCategoriesVO> list = productRepository.getProductCategories();

        ProductCategoriesVO allCategory = new ProductCategoriesVO();
        allCategory.setType("全部");

        if (!list.isEmpty()) {
            list.add(0, allCategory);
            int id = 0;
            for (ProductCategoriesVO productCategoriesVO : list) {
                productCategoriesVO.setId(id);
                id++;
            }
            return ApiResponse.success(list);
        }
        return ApiResponse.error("获取分类失败");
    }

    @Override
    public ApiResponse<List<ProductCategoriesVO>> getRandomCategories() {
        List<ProductCategoriesVO> list = productRepository.getProductCategories();
        log.info(list.toString());
        if (list.isEmpty()) {
            return ApiResponse.error("获取失败");
        }
        if (list.size() >= 4) {
            Collections.shuffle(list); // 打乱顺序
            list = list.subList(0, 4);
        }
        int id = 1;
        for (ProductCategoriesVO productCategoriesVO : list) {
            productCategoriesVO.setId(id);
            id++;
        }
        return ApiResponse.success(list);
    }

    @Override
    public ApiResponse<Boolean> getFavor(Favor favor) {
        Favor isFavor = productRepository.getFavor(favor);
        if (isFavor != null) {
            return ApiResponse.success(true);
        }
        return ApiResponse.success(false);
    }

    @Override
    public ApiResponse<String> editFavor(Favor favor) {
        int num;
        if (favor.getIsFavor()) {
            num = productRepository.addFavor(favor);
        } else {
            num = productRepository.removeFavor(favor);
        }
        if (num > 0) {
            return ApiResponse.success("修改成功");
        }
        return ApiResponse.error("修改失败");
    }


    @Override
    public ApiResponse<List<FavorWithProductVO>> getAllFavor(Favor favor) {
        List<Favor> favors = productRepository.getAllFavor(favor);
        ModelMapper modelMapper = new ModelMapper();
        List<FavorWithProductVO> favorWithProductVOList = favors.stream()
                .map(favorItem -> modelMapper.map(favorItem, FavorWithProductVO.class))
                .toList();

        for (FavorWithProductVO favorWithProductVO : favorWithProductVOList) {
            int productId = favorWithProductVO.getProductId();
            Product productInfo = productRepository.getProductById(productId);
            if (productInfo != null) {
                BeanUtils.copyProperties(productInfo, favorWithProductVO);
                log.info(favorWithProductVO.toString());
            }
        }
        if (!favorWithProductVOList.isEmpty()) {
            return ApiResponse.success(favorWithProductVOList);
        }
        return ApiResponse.error(201, "收藏为空");
    }
}
